package Sun

import java.io.{File, PrintWriter}

import ch.epfl.lamp.compiler.msil.emit.Label
import org.apache.spark.mllib.linalg.{Vectors, Vector}

import scala.io.Source


/**
 * Created by SHANGMAI on 2016/7/28.
 */

//模型预测的函数，里面有相关的权重变量等
class MutiTouchModel() extends Serializable {

  var weights: Vector = null

  //有了向量权重后进行预测
  def predict(data:Vector): Double =
  {
    //使用逻辑回归进行预测
    BasicFunction.logisticFuntion(data,weights)

  }


  //根据域值来进行预测
  def predict(data:Vector,threshold:Double): Double =
  {
    //使用逻辑回归进行预测，大于阈值的时候返回1 否则返回0
    if (BasicFunction.logisticFuntion(BasicFunction.getStaticFeatureC(data),BasicFunction.getStaticWeightC(weights)) >= threshold)
      return  1.0
    else
      return 0.0

  }

  //进行向量和数据的存储，这里直接存入redis，权重个数不会超过5000个  远远小于500M
  def saveModel(mode: String):Unit =
  {

    //如果是redis则存在redis里
    if (mode != "StandAlone") {
      val jedis = RedisClient.pool.getResource
      jedis.select(BasicFunction.dbIndex)
      jedis.set("MutiTouchModel",weights.toString)
      jedis.close()
    }

    else
    {
      //存在文件里
      val writer = new PrintWriter(new File(BasicFunction.modelweight_path))
      writer.write(weights.toArray.mkString(", "))
      writer.close()

    }

  }

  //进行权重读取,读取redis里面的内容
  def loadModel(mode: String):Unit =
  {
    if (mode != "StandAlone") {
      //进行K-V的储存
      val jedis = RedisClient.pool.getResource
      jedis.select(BasicFunction.dbIndex)
      val tempWeight = jedis.get("MutiTouchModel")
      weights = Vectors.dense(tempWeight.replace("[", "").replace("]", "").split(",").map(x => x.toDouble)).toSparse
      jedis.close()
    }

    //文件中读出
    else{
      //给出权重赋值
      val weightnow = Source.fromFile(BasicFunction.modelweight_path).take(0).toString()
      weights = Vectors.dense(weightnow.split(",").map(x => x.toDouble)).toSparse
    }
  }

  //通过直接读取向量来获得
  def loadModel(weight:Vector):Unit =
  {
    weights = weight
  }


}
